package com.ahcloud.edas.common.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @program: edas-common
 * @description:
 * @author: YuKai Fan
 * @create: 2024/4/20 09:24
 **/
@Slf4j
public abstract class ServiceThread implements Runnable {

    private static final long JOIN_TIME = 90 * 1000;

    protected Thread thread;

    protected volatile boolean stopped = false;

    protected boolean isDaemon = false;

    private final AtomicBoolean started = new AtomicBoolean(false);

    public ServiceThread() {
    }

    public abstract String getServiceName();

    public void start() {
        log.info("Try to start service thread:{} started:{} lastThread:{}", getServiceName(), started.get(), thread);
        if (!started.compareAndSet(false, true)) {
            return;
        }
        stopped = false;
        this.thread = new Thread(this, getServiceName());
        this.thread.setDaemon(isDaemon);
        this.thread.start();
    }

    public void shutdown() {
        this.shutdown(false);
    }

    public void shutdown(final boolean interrupt) {
        log.info("Try to shutdown service thread:{} started:{} lastThread:{}", getServiceName(), started.get(), thread);
        if (!started.compareAndSet(true, false)) {
            return;
        }
        this.stopped = true;
        log.info("shutdown thread {} interrupt {}", this.getServiceName(), interrupt);
//
//        if (hasNotified.compareAndSet(false, true)) {
//            waitPoint.countDown(); // notify
//        }

        try {
            if (interrupt) {
                this.thread.interrupt();
            }

            long beginTime = System.currentTimeMillis();
            if (!this.thread.isDaemon()) {
                this.thread.join(this.getJoinTime());
            }
            long elapsedTime = System.currentTimeMillis() - beginTime;
            log.info("join thread {} elapsed time(ms) {} {}", this.getServiceName(), elapsedTime, this.getJoinTime());
        } catch (InterruptedException e) {
            log.error("Interrupted", e);
        }
    }

    public long getJoinTime() {
        return JOIN_TIME;
    }

    public boolean isStopped() {
        return stopped;
    }

}
